<?php

namespace app\api\model\kuyou\applet;

use app\api\controller\kuyou\applet\Commons;
use think\Model;
use think\Db;
use Exception;
class UnitConversion extends Model
{

    // 表名
    protected $name = 'kuyou_unit';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = true;

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';


    /**
     * 获取列表
     * @param array $where
     * @param int $page
     * @param int $limit
     * @return array
     */
    public static function getList($where,$page,$limit){
        $app_page = config('app_page');
        $app_page = $app_page===false?false:true;
        $pageStatus = true;
        if($app_page){
            if($page<0){
                $pageStatus = false;
            }
        }
        if($pageStatus){
            $list = collection(self::where(function ($query) use ($where) {
                $query->where('type', '=', '2');
                $query->where('is_main', '=', '1');
                $query->where($where);
            })->page($page,$limit)->field("id,name,FROM_UNIXTIME(createtime,'%Y-%m-%d %H:%i:%s') as createtime,FROM_UNIXTIME(updatetime,'%Y-%m-%d %H:%i:%s') as updatetime")->select())->toArray();
        }else{
            $list = collection(self::where(function ($query) use ($where) {
                $query->where('type', '=', '2');
                $query->where('is_main', '=', '1');
                $query->where($where);
            })->field("id,name,FROM_UNIXTIME(createtime,'%Y-%m-%d %H:%i:%s') as createtime,FROM_UNIXTIME(updatetime,'%Y-%m-%d %H:%i:%s') as updatetime")->select())->toArray();
        }

        $lists = collection(self::where(function ($query) {
            $query->where('type', '=', '2');
        })->column('name',"id"))->toArray();
        foreach ($list as $list_k=>$list_v){
            $unit = collection((new UnitConversions())
                ->where(['main_unit'=>$list_v['id']])
                ->order('advance_rate','ASC')
                ->field('vice_unit,advance_rate')->select())->toArray();
            $list_v['advance_rate'] = '1';
            foreach ($unit as $unit_k=>$unit_v){
                $list_v['name'] .= ','.(isset($lists[$unit_v['vice_unit']])?$lists[$unit_v['vice_unit']]:'');
                $list_v['advance_rate'] .= ':'.$unit_v['advance_rate'];
            }
            $list[$list_k] = $list_v;
        }

        $count = self::where(function ($query) use ($where) {
            $query->where('type', '=', '2');
            $query->where('is_main', '=', '1');
            $query->where($where);
        })->count();
        return ['list'=>$list,'count'=>$count];
    }

    /**
     * 获取详情
     * @param int $id
     * @return array
     */
    public static function getDetail($id){
        $detail = self::where(function ($query) use ($id) {
            $query->where('id', '=', $id);
            $query->where('type', '=', '2');
            $query->where('is_main', '=', '1');
        })->field("id,name,FROM_UNIXTIME(createtime,'%Y-%m-%d %H:%i:%s') as createtime,FROM_UNIXTIME(updatetime,'%Y-%m-%d %H:%i:%s') as updatetime")->find();

        $lists = collection(self::where(function ($query) {
            $query->where('type', '=', '2');
        })->column('name',"id"))->toArray();

        if($detail){
            $unit = collection((new UnitConversions())
                ->where(['main_unit'=>$detail['id']])
                ->order('advance_rate','ASC')
                ->field('vice_unit as id,advance_rate')->select())->toArray();
            foreach ($unit as $unit_k=>$unit_v){
                $unit[$unit_k]['name'] = $lists[$unit_v['id']];
            }
            $detail['unit'] = $unit;
            return $detail;
        }else{
            return ['status'=>500,'msg'=>'为查询到数据'];
        }
    }

    /**
     * 添加
     * @param array $detail
     * @return array
     */
    public static function addDetail($detail){
        if(empty($detail)){
            return ['status'=>400,'msg'=>'参数错误'];
        }else{
            $check = (new Commons())->checkParameter($detail,[
                'name|名称'=>'require',
                'sub_unit|副单位'=>'require',
            ]);
            if(isset($check['status'])){
                return $check;
            }else{
                $sub_unit = $detail['sub_unit'];
                Db::startTrans();
                try {
                    $main_unit = (new Unit())->insertGetId([
                        'name'          => $detail['name'],
                        'type'          => '2',
                        'is_main'       => '1',
                        'createtime'    => time(),
                        'updatetime'    => time()
                    ]);
                    foreach ($sub_unit as $data_k=>$data_v){
                        $vice_unit = (new Unit())->insertGetId([
                            'name'          => $data_v['name'],
                            'type'          => '2',
                            'is_main'       => '0',
                            'createtime'    => time(),
                            'updatetime'    => time()
                        ]);
                        if($vice_unit){
                            (new UnitConversions())->insert([
                                'unit_name'     => $detail['name'].'/'.$data_v['name'],
                                'main_unit'     => $main_unit,
                                'vice_unit'     => $vice_unit,
                                'advance_rate'  => $data_v['advance_rate'],
                                'createtime'    => time(),
                                'updatetime'    => time()
                            ]);
                        }
                    }
                    Db::commit();
                } catch (Exception $e) {
                    Db::rollback();
                    return ['status'=>500,'msg'=>$e->getMessage()];
                }
                if($main_unit){
                    return ['status'=>200,'msg'=>$main_unit];
                }else{
                    return ['status'=>500,'msg'=>'添加失败'];
                }
            }
        }
    }

    /**
     * 更新
     * @param array $detail
     * @return array
     */
    public static function editDetail($detail){
        if(empty($detail)){
            return ['status'=>400,'msg'=>'参数错误'];
        }else{
            $check = (new Commons())->checkParameter($detail,[
                'id|ID'=>'require|number',
                'name|名称'=>'require',
                'sub_unit|副单位'=>'require',
            ]);
            if(isset($check['status'])){
                return $check;
            }else{
                $id = $detail['id'];unset($detail['id']);
                $goods = (new Goods())->where(['more_unit_id'=>$id])->find();
                if($goods){
                    return ['status'=>500,'msg'=>'此单位已参与商品核算，不可编辑'];
                }
                $sub_unit = $detail['sub_unit'];
                $vid = (new UnitConversions())->where(['main_unit'=>$id])->column('vice_unit');
                Db::startTrans();
                try {
                    (new UnitConversions())->where(['main_unit'=>$id])->delete();
                    (new Unit())->where(['id'=>['in',$vid]])->delete();
                    (new Unit())->where(['id'=>$id])->update([
                        'name'          => $detail['name'],
                        'type'          => '2',
                        'is_main'       => '1',
                        'updatetime'    => time()
                    ]);
                    $main_unit = $id;
                    foreach ($sub_unit as $data_k=>$data_v){
                        $vice_unit = (new Unit())->insertGetId([
                            'name'          => $data_v['name'],
                            'type'          => '2',
                            'is_main'       => '0',
                            'createtime'    => time(),
                            'updatetime'    => time()
                        ]);
                        if($vice_unit){
                            (new UnitConversions())->insert([
                                'unit_name'     => $detail['name'].'/'.$data_v['name'],
                                'main_unit'     => $main_unit,
                                'vice_unit'     => $vice_unit,
                                'advance_rate'  => $data_v['advance_rate'],
                                'createtime'    => time(),
                                'updatetime'    => time()
                            ]);
                        }
                    }
                    Db::commit();
                } catch (Exception $e) {
                    Db::rollback();
                    return ['status'=>500,'msg'=>$e->getMessage()];
                }
                if($main_unit){
                    return ['status'=>200,'msg'=>$main_unit];
                }else{
                    return ['status'=>500,'msg'=>'添加失败'];
                }
            }
        }
    }

    /**
     * 删除
     * @param int $id
     * @return array
     */
    public static function delDetail($id){
        if(empty($id)){
            return ['status'=>400,'msg'=>'参数错误'];
        }else{
            $goods = (new Goods())->where(['more_unit_id'=>['in',$id]])->find();
            if($goods){
                return ['status'=>500,'msg'=>'此单位已参与商品核算，不可删除'];
            }
            $ids = explode(',',$id);
            $vid = (new UnitConversions())->where(['main_unit'=>['in',$id]])->column('vice_unit');

            Db::startTrans();
            try {
                (new UnitConversions())->where(['main_unit'=>['in',$id]])->delete();
                (new Unit())->where(['id'=>['in',$vid]])->delete();
                $res = (new Unit())->where(['id'=>['in',$ids]])->delete();
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                return ['status'=>500,'msg'=>$e->getMessage()];
            }

            if($res){
                return ['status'=>200,'msg'=>$res];
            }else{
                return ['status'=>500,'msg'=>'删除失败'];
            }
        }
    }
}
